#! /bin/bash
#   
# Elasticsearch - this script starts and stops the Elasticsearch daemon
#   
# chkconfig:    2345 80 90
# description:  Elasticsearch
#   
### BEGIN INIT INFO
# Provides:          Elasticsearch
# Required-Start:    $syslog
# Required-Stop:     $syslog
# Should-Start:        $local_fs
# Should-Stop:        $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description:    Elasticsearch daemon
# Description:        Elasticsearch daemon
### END INIT INFO

# Those env variables will be auto replace by autoinstall shell, do not modify!!!
PATH=YOURPATH
ELK_Install_Dir=YOURELK_Install_Dir
Elasticsearch_Ver=YOURElasticsearch_Ver
CURRNET_IP=`hostname -I`

Color_Text()
{
  echo -e " \e[0;$2m$1\e[0m"
}

Echo_Green()
{
  echo $(Color_Text "$1" "32")
}

Echo_Red()
{
  echo $(Color_Text "$1" "31")
}
   
case "$1" in
    start)
		su - yusp -c "${ELK_Install_Dir}/elasticsearch-${Elasticsearch_Ver}/bin/elasticsearch -E network.host=${CURRNET_IP} -d -p pid"
		if [ $? -eq 0 ]; then
			Echo_Green "OK, ====== start Elasticsearch Successful!!======"
		else
			echo "Sorry, start Elasticsearch failed! please check you operation and try again!"
			return -1;
		fi
        ;;
    stop)
        echo "Shutting down Elasticsearch..."
		kill $(cat ${ELK_Install_Dir}/elasticsearch-${Elasticsearch_Ver}/pid)
		if [ $? -eq 0 ]; then
			Echo_Green "OK, ====== Stop Elasticsearch Successful!!======"
		else
			echo "Sorry, Stop Elasticsearch failed! please check you operation and try again!"
			return -1;
		fi
        ;;
    restart)
        ${0} stop
        ${0} start
        ;;
    kill)
        echo "Shutting down Elasticsearch..."
		kill $(cat ${ELK_Install_Dir}/elasticsearch-${Elasticsearch_Ver}/pid)
		if [ $? -eq 0 ]; then
			Echo_Green "OK, ====== Stop Elasticsearch Successful!!======"
		else
			echo "Sorry, Stop Elasticsearch failed! please check you operation and try again!"
			return -1;
		fi
        ;;
    status)
		curl -s "${CURRNET_IP}:9200"
        if [ $? -eq 0 ]; then
            Echo_Green "elasticsearch is running."
        else
            Echo_Red "elasticsearch is stopped."
        fi
        ;;
  *)
    echo "Usage: /etc/init.d/elasticsearch {start|stop|restart|status|kill}" >&2
        exit 1
esac
